import time
import redis
import logging
from opcua import Client
import csv

TagNames = []

# 读取CSV文件，注意最后不要有空行
filename = './data/test.csv'
with open(filename, "r") as csvfile:
    csvreader = csv.reader(csvfile)
    # next(csvreader, None)  # 跳过表头
    # 遍历csvreader对象的每一行内容并输出
    for row in csvreader:
        TagNames.append(row[0])

# 连接到OPC服务器
client = Client("opc.tcp://192.168.152.196:49326")
client.connect()

# 连接redis
r = redis.Redis(host='192.168.152.147', port=6379, db=0)

# 创建logger对象
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)

# 创建FileHandler对象
fh = logging.FileHandler('mylog.log')
fh.setLevel(logging.DEBUG)

# 创建Formatter对象
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 将FileHandler对象添加到Logger对象中
logger.addHandler(fh)

# 根据TAG名字读取Node
Nodes = []
for TagName in TagNames:
    Nodes.append(client.get_node(TagName))

# 根据Node读取Value
while True:
    values = client.get_values(Nodes)
    for node_path, value in zip(TagNames, values):
        logger.info(f"TAG名字 = {node_path} ,值 = {round(value,2)}")
        r.set(node_path, round(value,2))

    time.sleep(1)